use notify::{Config, RecommendedWatcher, Watcher};
use tokio::{
    io::{AsyncBufReadExt, AsyncSeekExt},
    task::JoinHandle,
    time::{sleep, Duration},
};
use std::time::SystemTime;
use anyhow::{Result, anyhow};

use crate::rpc_server::{rpc_server, RpcServerImpl};
use crate::config::AgentConfig;
use crate::connection_manager::ConnectionManager;

pub struct MyAgentWithRetry {
    /// Agent配置信息
    config: AgentConfig,
    /// 连接管理器
    connection_manager: ConnectionManager,
}

impl MyAgentWithRetry {
    pub fn new(config: AgentConfig) -> Self {
        let connection_manager = ConnectionManager::new(&config);
        Self { 
            config,
            connection_manager,
        }
    }

    /// 运行agent with retry capability
    pub async fn run(&mut self) -> Result<()> {
        log::info!("启动Agent with故障处理能力");
        log::info!("Agent配置: ID={}, Server地址={:?}", 
                   self.config.agent_id, self.config.server_urls);
        
        // 启动RPC服务器
        let rpc_handler = self.start_rpc_server().await;
        
        // 启动主循环 - 包含注册和心跳
        let main_loop_handler = self.start_main_loop();
        
        // 启动配置文件监控
        let monitor_handler = self.monitor_config_file().await;
        
        // 等待所有任务完成
        tokio::try_join!(rpc_handler, main_loop_handler, monitor_handler)?;
        Ok(())
    }

    /// 主循环 - 处理注册、心跳和重连
    async fn start_main_loop(&mut self) -> JoinHandle<Result<()>> {
        let mut connection_manager = ConnectionManager::new(&self.config);
        let config = self.config.clone();
        
        tokio::spawn(async move {
            let mut registered = false;
            let mut last_heartbeat = SystemTime::UNIX_EPOCH;
            let heartbeat_interval = config.health_check.heartbeat_interval();
            
            loop {
                // 确保连接可用
                match connection_manager.ensure_connection().await {
                    Ok(client) => {
                        // 如果还没注册，先注册
                        if !registered {
                            match Self::register_agent(client, &config).await {
                                Ok(_) => {
                                    log::info!("Agent注册成功");
                                    registered = true;
                                    last_heartbeat = SystemTime::now();
                                }
                                Err(e) => {
                                    log::error!("Agent注册失败: {}", e);
                                    registered = false;
                                }
                            }
                        } else {
                            // 发送心跳
                            let now = SystemTime::now();
                            if now.duration_since(last_heartbeat).unwrap_or_default() >= heartbeat_interval {
                                match Self::send_heartbeat(client, &config).await {
                                    Ok(_) => {
                                        log::debug!("心跳发送成功");
                                        last_heartbeat = now;
                                    }
                                    Err(e) => {
                                        log::warn!("心跳发送失败: {}", e);
                                        registered = false; // 需要重新注册
                                    }
                                }
                            }
                        }
                    }
                    Err(e) => {
                        log::error!("连接失败: {}", e);
                        registered = false;
                        
                        // 连接失败时等待一段时间再重试
                        tokio::time::sleep(Duration::from_secs(10)).await;
                        continue;
                    }
                }
                
                // 等待一段时间再进行下次循环
                tokio::time::sleep(Duration::from_secs(5)).await;
            }
        })
    }

    async fn register_agent(
        client: &mut crate::rpc_client::config_monitor_client::ConfigMonitorClient<tonic::transport::Channel>,
        config: &AgentConfig,
    ) -> Result<()> {
        log::info!("正在向Server注册: {:?}", config.server_urls);
        log::info!("Agent ID: {}", config.agent_id);
        log::info!("Agent标签: {:?}", config.labels);
        
        // 创建AgentInfo
        let agent_info = crate::rpc_client::AgentInfo {
            agent_id: config.agent_id.clone(),
            agent_address: config.get_external_address(),
            hostname: hostname::get().unwrap_or_default().to_string_lossy().to_string(),
            labels: config.labels.clone(),
            last_heartbeat: chrono::Utc::now().timestamp(),
        };
        
        let request = crate::rpc_client::RegisterAgentRequest { 
            agent_info: Some(agent_info)
        };
        
        let response = client.register_agent(tonic::Request::new(request)).await?;
        let resp = response.into_inner();
        
        log::info!("注册成功: {}", resp.message);
        if !resp.assigned_groups.is_empty() {
            log::info!("自动分配到组: {:?}", resp.assigned_groups);
        }
        
        Ok(())
    }

    async fn send_heartbeat(
        client: &mut crate::rpc_client::config_monitor_client::ConfigMonitorClient<tonic::transport::Channel>,
        config: &AgentConfig,
    ) -> Result<()> {
        let request = crate::rpc_client::HeartbeatRequest {
            agent_id: config.agent_id.clone(),
            timestamp: chrono::Utc::now().timestamp(),
            status: "online".to_string(),
        };
        
        let _response = client.heartbeat(tonic::Request::new(request)).await?;
        Ok(())
    }

    async fn start_rpc_server(&self) -> JoinHandle<Result<()>> {
        let addr = match self.config.addr.clone().parse() {
            Ok(addr) => addr,
            Err(e) => {
                log::error!("解析地址失败: {:?}", e);
                return tokio::spawn(async { Err(anyhow!("地址解析失败")) });
            }
        };

        log::info!("启动RPC服务器: {}", addr);
        
        tokio::spawn(async move {
            let rpc_server_impl = RpcServerImpl::new();
            let svc = rpc_server::rpc_a_server::RpcAServer::new(rpc_server_impl);
            
            match tonic::transport::Server::builder()
                .add_service(svc)
                .serve(addr)
                .await
            {
                Ok(_) => {
                    log::info!("RPC服务器正常退出");
                    Ok(())
                }
                Err(e) => {
                    log::error!("RPC服务器错误: {:?}", e);
                    Err(anyhow!("RPC服务器错误: {}", e))
                }
            }
        })
    }

    async fn monitor_config_file(&self) -> JoinHandle<Result<()>> {
        tokio::spawn(async move {
            log::info!("启动配置文件监控");
            
            // 这里保持原有的文件监控逻辑
            // 为了简化，暂时返回成功
            loop {
                tokio::time::sleep(Duration::from_secs(60)).await;
                log::debug!("配置文件监控运行中...");
            }
        })
    }
}

// 为了向后兼容，保留原有的MyAgent结构
pub use MyAgentWithRetry as MyAgent;